package org.lex.depends.core.resource;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.commons.io.IOCase;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.lex.io.utils.FileUtils;

public class ClassUtils {

	public static void loadFileSystemResource(File dir, Map<String, IResource> map, Map<String, File> nameLocationMap) {
		String root = dir.getAbsolutePath();
		int len = root.length();

		FileFilter filter = new SuffixFileFilter(".class", IOCase.INSENSITIVE);
		Collection<File> files = FileUtils.listFiles(dir, filter);
		for (File file : files) {
			String name = file.getAbsolutePath();
			name = name.substring(len + 1);
			int dotIndex = name.lastIndexOf('.');
			if (-1 != dotIndex) {
				name = name.substring(0, dotIndex);
			}
			name = name.replace('\\', '.');
			map.put(name, new FileResource(file));
			nameLocationMap.put(name, dir);
		}
	}

	public static void loadJarResource(File jar, Map<String, IResource> map, Map<String, File> nameLocationMap)
			throws IOException {
		JarFile file = new JarFile(jar);
		Enumeration<JarEntry> entries = file.entries();
		while (entries.hasMoreElements()) {
			JarEntry e = entries.nextElement();
			if (false == e.isDirectory()) {
				String name = e.getName();
				String className = getClassName(name);
				if (null != className) {
					InputStream is = file.getInputStream(e);
					byte[] data = IOUtils.toByteArray(is);
					IOUtils.closeQuietly(is);
					map.put(className, new ByteResource(data));
					nameLocationMap.put(className, jar);
				}
			}
		}
	}

	/**
	 * 
	 * @param path
	 *            like "org/lex/Main.class"
	 * @return
	 */
	public static String getClassName(String path) {
		String className = null;
		int dotIndex = path.lastIndexOf('.');
		if (-1 != dotIndex && dotIndex < path.length() - 1) {
			String suffix = path.substring(dotIndex + 1);
			if (suffix.toLowerCase().equals("class")) {
				className = path.substring(0, dotIndex);
				className = className.replace('/', '.');
			}
		}
		return className;
	}
}
